import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { SearchRoleDto } from './dto/search-role.dto';
import { Result } from 'src/utils/result';
import { Role } from './entities/role.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { SysRoleMenu } from './entities/role-with-menu.entity';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private readonly sysRoleEntity: Repository<Role>,
    @InjectRepository(SysRoleMenu)
    private readonly sysRoleMenuEntity: Repository<SysRoleMenu>,
  ) {}
  async create(createRoleDto: CreateRoleDto) {
    const role = await this.sysRoleEntity.save(createRoleDto);
    const roleMenuBuilder = this.sysRoleMenuEntity.createQueryBuilder('entity');
    const values = createRoleDto.menuIds.map((menuId) => ({
      roleId: role.roleId,
      menuId,
    }));
    await roleMenuBuilder.insert().values(values).execute();
    return Result.success();
  }
  // 查询角色列表
  async findAllByPage(query: SearchRoleDto) {
    const roleBuilder = this.sysRoleEntity.createQueryBuilder();
    roleBuilder.skip((query.pageNum - 1) * query.pageSize).take(query.pageSize);
    const [list, total] = await roleBuilder.getManyAndCount();
    return Result.success({ list, total });
  }

  // 查询所有角色
  async findAll() {
    const roleList = await this.sysRoleEntity.find();
    return Result.success(roleList);
  }

  // 查询角色
  async findOne(roleId: number) {
    const role = await this.sysRoleEntity.findOne({
      where: { roleId },
    });
    const menuIds = await this.sysRoleMenuEntity
      .find({
        where: { roleId },
        select: ['menuId'],
      })
      .then((res) => res.map((item) => item.menuId));
    return Result.success({ ...role, menuIds });
  }
  // 更新角色
  async update(roleId: number, updateRoleDto: UpdateRoleDto) {
    const hasRole = await this.sysRoleMenuEntity.findOne({
      where: { roleId },
    });
    if (hasRole) {
      this.sysRoleMenuEntity.delete({ roleId });
    }
    const roleMenuBuilder = this.sysRoleMenuEntity.createQueryBuilder('entity');
    const values = updateRoleDto.menuIds.map((menuId) => ({
      roleId,
      menuId,
    }));
    delete updateRoleDto.menuIds;
    await this.sysRoleEntity.update(roleId, updateRoleDto);
    await roleMenuBuilder.insert().values(values).execute();
    return Result.success();
  }

  async remove(roleId: number) {
    const hasRole = await this.sysRoleMenuEntity.findOne({
      where: { roleId },
    });
    if (hasRole) {
      this.sysRoleMenuEntity.delete({ roleId });
    }
    await this.sysRoleEntity.delete(roleId);
    return Result.success();
  }
}
